<template>
  <div class="db-config-container">
    <div class="page-header">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增数据库
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :model="searchForm" label-width="100px" :inline="true">
        <el-form-item label="数据库类型">
          <el-select 
            v-model="searchForm.db_type" 
            placeholder="全部" 
            clearable 
            class="db-type-select">
            <el-option label="MySql" value="mysql" />
            <el-option label="Fabric SQL Server" value="fabric_sqlserver" />
            <el-option label="SQL Server" value="sqlserver" />
          </el-select>
        </el-form-item>
        <el-form-item label="连接名称">
          <el-input v-model="searchForm.connection_name" placeholder="输入连接名称" clearable />
        </el-form-item>
        <el-form-item label="主机地址">
          <el-input v-model="searchForm.host" placeholder="输入主机地址" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><RefreshLeft /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据库列表 -->
    <el-card shadow="hover" class="list-card">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="connection_name" label="连接名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="db_type" label="数据库类型" min-width="120">
          <template #default="scope">
            <el-tag :type="getDbTypeTagType(scope.row.db_type)">{{ scope.row.db_type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="host" label="主机地址" min-width="150" show-overflow-tooltip />
        <el-table-column prop="port" label="端口" min-width="80" />
        <el-table-column prop="database_name" label="数据库名" min-width="150" show-overflow-tooltip />
        <el-table-column prop="username" label="用户名" min-width="120" show-overflow-tooltip />
        <el-table-column prop="created_by" label="创建人" min-width="120" show-overflow-tooltip />
        <el-table-column label="创建时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="updated_by" label="更新人" min-width="120" show-overflow-tooltip />
        <el-table-column label="更新时间" min-width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="success" @click="handleTest(scope.row)">测试连接</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增数据库配置' : '编辑数据库配置'"
      width="650px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="db-form"
        :disabled="formLoading"
      >
        <el-form-item label="连接名称" prop="connection_name">
          <el-input v-model="form.connection_name" placeholder="请输入连接名称" />
        </el-form-item>
        <el-form-item label="数据库类型" prop="db_type">
          <el-select v-model="form.db_type" placeholder="请选择数据库类型" class="db-type-select">
            <el-option label="MySql" value="mysql" />
            <el-option label="Fabric SQL Server" value="fabric_sqlserver" />
            <el-option label="SQL Server" value="sqlserver" />
          </el-select>
        </el-form-item>
        <el-form-item label="主机地址" prop="host">
          <el-input v-model="form.host" placeholder="请输入主机地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input-number v-model="form.port" :min="1"  controls-position="right" />
        </el-form-item>
        <el-form-item label="数据库名" prop="database_name">
          <el-input v-model="form.database_name" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="连接字符串扩展">
          <el-input
            v-model="form.connection_string_ext"
            type="textarea"
            :rows="2"
            placeholder="可选，特殊连接参数，例如：charset=utf8&connectTimeout=10000"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTestInForm" :loading="testLoading">测试连接</el-button>
          <el-button type="success" @click="submitForm" :loading="formLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import { Plus, Search, RefreshLeft } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { getDBConfigList, getDBConfigDetail, createDBConfig, updateDBConfig, deleteDBConfig, testDBConnection } from '@/api/db-config';

// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();

// 表格数据和加载状态
const tableData = ref<any[]>([]);
const tableLoading = ref(false);

// 搜索表单
const searchForm = reactive({
  db_type: '',
  connection_name: '',
  host: ''
});

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框控制
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');

// 表单数据
const form = reactive({
  id: '',
  connection_name: '',
  db_type: '',
  host: '',
  port: 3306,
  database_name: '',
  username: '',
  password: '',
  connection_string_ext: '',
});

// 表单校验规则
const rules = reactive({
  connection_name: [
    { required: true, message: '请输入连接名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2-50个字符之间', trigger: 'blur' }
  ],
  db_type: [
    { required: true, message: '请选择数据库类型', trigger: 'change' }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' }
  ],
  // port: [
  //   { required: true, message: '请输入端口号', trigger: 'blur' }
  // ],
  database_name: [
    { required: true, message: '请输入数据库名', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});

// 加载状态
const formLoading = ref(false);
const testLoading = ref(false);

// 获取数据库类型标签样式
const getDbTypeTagType = (dbType: string) => {
  const typeMap: Record<string, string> = {
    mysql: 'primary',
    postgresql: 'success',
    sqlserver: 'warning',
    oracle: 'danger'
  };
  return typeMap[dbType.toLowerCase()] || 'info';
};

// 格式化日期时间
const formatDateTime = (dateTime: string | number | Date) => {
  return dateTime ? dayjs(dateTime).format('YYYY-MM-DD HH:mm:ss') : '';
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1; // 重置为第一页
  fetchDBConfigList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof typeof searchForm] = '';
  });
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchDBConfigList();
};

// 处理页码变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchDBConfigList();
};

// 获取数据库配置列表
const fetchDBConfigList = async () => {
  try {
    tableLoading.value = true;
    const response: any = await getDBConfigList({
      ...searchForm,
      page: pagination.currentPage,
      size: pagination.pageSize
    });
    
    if (response.code === 200) {
      tableData.value = response.data.list || [];
      pagination.total = response.data.total || 0; // 确保使用后端返回的总记录数
    } else {
      ElMessage.error(response.message || '获取数据库配置列表失败');
    }
  } catch (error) {
    console.error('获取数据库配置列表出错:', error);
    ElMessage.error('获取数据库配置列表出错');
  } finally {
    tableLoading.value = false;
  }
};

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add';
  resetForm();
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row: any) => {
  dialogType.value = 'edit';
  resetForm();
  
  try {
    formLoading.value = true;
    const response: any = await getDBConfigDetail(row._id);
    
    if (response.code === 200 && response.data) {
      Object.assign(form, response.data);
      form.id = row._id; // 确保ID被正确设置
    } else {
      ElMessage.error(response.message || '获取数据库配置详情失败');
    }
  } catch (error) {
    console.error('获取数据库配置详情出错:', error);
    ElMessage.error('获取数据库配置详情出错');
  } finally {
    formLoading.value = false;
  }
  
  dialogVisible.value = true;
};

// 处理表单内测试连接
const handleTestInForm = async () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    
    try {
      testLoading.value = true;
      const response: any = await testDBConnection(form);
      
      if (response.code === 200) {
        ElMessage.success(response.message || '连接测试成功');
      } else {
        ElMessage.error(response.message || '连接测试失败');
      }
    } catch (error) {
      console.error('测试数据库连接出错:', error);
      ElMessage.error('测试数据库连接出错');
    } finally {
      testLoading.value = false;
    }
  });
};

// 处理列表中的测试连接
const handleTest = async (row: any) => {
  try {
    debugger
    const response: any = await testDBConnection({ id: row._id });
    
    if (response.code === 200) {
      ElMessage.success(response.message || '连接测试成功');
    } else {
      ElMessage.error(response.message || '连接测试失败');
    }
  } catch (error) {
    console.error('测试数据库连接出错:', error);
    ElMessage.error('测试数据库连接出错');
  }
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除该数据库配置吗？删除后不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response: any = await deleteDBConfig(row._id);
      if (response.code === 200) {
        ElMessage.success(response.message || '删除成功');
        fetchDBConfigList(); // 重新加载列表
      } else {
        ElMessage.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除数据库配置出错:', error);
      ElMessage.error('删除数据库配置出错');
    }
  }).catch(() => {});
};

// 重置表单
const resetForm = () => {
  form.id = '';
  form.connection_name = '';
  form.db_type = '';
  form.host = '';
  form.port = 3306; // 默认端口
  form.database_name = '';
  form.username = '';
  form.password = '';
  form.connection_string_ext = '';
  
  // 清除表单验证结果
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    
    try {
      formLoading.value = true;
      let response;
      
      if (dialogType.value === 'add') {
        response = await createDBConfig(form);
      } else {
        debugger
        const { id, ...updateData } = form;
        response = await updateDBConfig(id, updateData);
      }
      
      if (response.code === 200) {
        ElMessage.success(response.message || (dialogType.value === 'add' ? '新增成功' : '更新成功'));
        dialogVisible.value = false;
        fetchDBConfigList(); // 重新加载列表
      } else {
        ElMessage.error(response.message || (dialogType.value === 'add' ? '新增失败' : '更新失败'));
      }
    } catch (error) {
      console.error(dialogType.value === 'add' ? '创建数据库配置出错:' : '更新数据库配置出错:', error);
      ElMessage.error(dialogType.value === 'add' ? '创建数据库配置出错' : '更新数据库配置出错');
    } finally {
      formLoading.value = false;
    }
  });
};

// 页面初始化
onMounted(() => {
  fetchDBConfigList();
});
</script>

<style lang="scss" scoped>
.db-config-container {
  // padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .page-title {
      font-size: 22px;
      font-weight: 600;
    }
  }
  
  .search-card {
    margin-bottom: 20px;

    .db-type-select {
      width: 180px !important; // 固定宽度并提高优先级
    }
    
    :deep(.el-select) {
      width: 180px !important; // 确保select元素也应用固定宽度
    }
    
    :deep(.el-input) {
      width: 220px; // 设置输入框宽度一致
    }
  }

  .list-card {
    :deep(.el-table) {
      // 确保表格内容超出时的处理
      .cell {
        white-space: nowrap;
      }

      // 强化tooltip的显示效果
      .el-tooltip__trigger {
        width: 100%;
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  // 弹窗内的表单控件样式
  .db-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .db-type-select {
      width: 100% !important; // 表单内的下拉框宽度设为100%
    }

    :deep(.el-input-number) {
      width: 180px;
    }
  }
}
</style>